import React, { PureComponent } from 'react'
import { connect } from '@umijs/max'
import { FormOutlined } from '@ant-design/icons'
import { Button, Dropdown, Menu, Modal, Tabs } from 'antd'
import Tools from '@/utils/Tools'
import { DataDevTree } from './page-components'
import { ArrowIcon, BlueSquare } from '../../components'
import { MonacoEditor } from '@/components'
import styles from './index.less'
import emptyImgNotWiFi from '@/assets/images/emptyImgScriptDev.png'

const Bus = Tools.Bus
const TabPane = Tabs.TabPane

@connect(({ scriptDev }) => ({ ...scriptDev }))
export default class Offline extends PureComponent {
  constructor(props) {
    super(props)
    this.state = {
      isShow: styles.data_dev_left,
      selectedKeys: [],
      currentClosingTask: null,
      closeModalVisible: false,
    }

    this.menus = (item) => (
      <Menu>
        <Menu.Item
          key="1"
          onClick={(event) => {
            this.onEditTask(item.id)
            event.domEvent.stopPropagation()
          }}
        >
          关闭
        </Menu.Item>
        <Menu.Item
          key="2"
          onClick={(event) => {
            this.props.dispatch({
              type: 'scriptDev/deleteAllTaskId',
              params: {
                ids: [item.id],
              },
            })
            event.domEvent.stopPropagation()
          }}
        >
          关闭其他
        </Menu.Item>
        <Menu.Item
          key="4"
          onClick={(event) => {
            this.props.dispatch({
              type: 'scriptDev/deleteAllTaskId',
            })
            event.domEvent.stopPropagation()
          }}
        >
          关闭全部
        </Menu.Item>
      </Menu>
    )
  }

  componentDidMount() {
  }

  // 树状列表右侧收缩按钮
  shousuo = (bool) => {
    if (bool) {
      this.setState(
        {
          isShow: styles.data_dev_left,
        },
        () => {
          if (this.props.activeKey) {
            Bus.emit('editorLayout', this.props.activeKey)
          }
        },
      )
    } else {
      this.setState(
        {
          isShow: `${styles.data_dev_left} ${styles.data_dev_left_show}`,
        },
        () => {
          if (this.props.activeKey) {
            Bus.emit('editorLayout', this.props.activeKey)
          }
        },
      )
    }
  }

  /**
   * 任务开发删除编辑项
   * @param {String} targetKey
   * @param {Boolean} forceClose 是否强制关闭，不触发弹框
   */
  onEditTask = (targetKey, forceClose = false) => {
    const { tasks } = this.props
    const item = tasks.find((task) => targetKey == task.id)
    // 数据开发任务编辑状态下，若有发生内容编辑，则在标签任务名称旁边显示已编辑的图标；
    if (item) {
      if (!forceClose) {
        if (item.hasEdited) {
          this.setState({
            currentClosingTask: item,
            closeModalVisible: true,
          })
          return
        }
      }
      this.props.dispatch({
        type: 'scriptDev/deleteTaskId',
        params: {
          id: item.id,
        },
      })
    }
  }

  // 树状列表选择回调
  onSelect = (selectedKeys) => {
    this.setState({
      selectedKeys,
    }, () => {
      if (selectedKeys.length > 0) {
        const targetKey = selectedKeys[0]
        const item = this.getTask(targetKey)
        if (item.nodeType) {
          this.props.dispatch({
            type: 'scriptDev/taskTabsHandle',
            params: {
              id: targetKey,
            },
            cb: () => {
              Bus.emit('editorLayout', targetKey)
            },
          })
        }
      }
    })
  }

  // tab页选择回调
  tabsChangeTask = (activeKey) => {
    this.props.dispatch({
      type: 'scriptDev/changeActiveKey',
      params: {
        id: `${activeKey}`,
      },
      cb: () => {
        Bus.emit('editorLayout', activeKey)
      },
    })
  }

  // 根据id找到任务对象
  getTask = (id) => {
    const { treeLists } = this.props
    return treeLists.find((item) => id == item.id)
  }

  /**
   * 编辑器内容发生改变时的事件
   * @param {String} tabKey
   * @param {Boolean} hasChanged
   */
  editorContentChange = (tabKey, hasChanged) => {
    const { tasks } = this.props
    const item = tasks.find((task) => tabKey == task.id)
    if (item) {
      const obj = { ...item }
      if (obj.hasEdited !== hasChanged) {
        obj.hasEdited = hasChanged
        this.props.dispatch({
          type: 'scriptDev/setTaskTabsEdie',
          params: {
            item: obj,
          },
        })
      }
    }
  };

  // 任务参数发生改变
  taskParamValChange = (val, key, id) => {
    const { dispatch } = this.props
    dispatch({
      type: this.props.navKey === 5 ? 'scriptDev/curstoMvariablesMr' : 'scriptDev/curstoMvariablesTask',
      params: {
        paramValue: val,
        id,
        key,
        bool: true,
      },
    })
  }

  // 更新自定义参数
  curstoMvariablesTask = (task, arr) => {
    this.props.dispatch({
      type: 'scriptDev/curstoMvariablesTask',
      params: {
        task,
        arr,
      },
    })
  }

  render() {
    const {
      isShow, selectedKeys, currentClosingTask, closeModalVisible,
    } = this.state
    const { taskIds, tasks, activeKey } = this.props
    return (
      <div className={styles.data_dev} id="scriptDevNode">
        <div className={isShow}>
          <DataDevTree
            title="作业目录"
            selectedKeys={selectedKeys}
            onSelect={this.onSelect}
          />
        </div>
        <div className={styles.data_dev_right}>
          <div
            className={styles.data_dev_right_box}
            style={{ width: '100%', height: '100%' }}
          >
            <ArrowIcon
              shousuoFun={this.shousuo}
            />
            {(tasks && tasks.length) ? (
              <div className={styles.editor_box}>
                <Tabs
                  type="editable-card"
                  onChange={this.tabsChangeTask}
                  activeKey={String(activeKey)}
                  animated
                  onEdit={(tabKey) => {
                    this.onEditTask(tabKey)
                  }}
                  className={`${styles.page_content_tabs} ${styles.editor_box_tabs}`}
                  hideAdd
                >
                  {tasks.map((item) => (
                    <TabPane
                      style={{ width: '100%', height: '100%' }}
                      tab={
                        <Dropdown
                          overlay={this.menus(item)}
                          trigger={['contextMenu']}
                        >
                          <div
                            title={item.name}
                            style={{
                              height: '100%',
                              width: '1.42rem',
                              overflow: 'hidden',
                              float: 'left',
                              textOverflow: 'ellipsis',
                              whiteSpace: 'nowrap',
                              fontSize: '0.14rem',
                              fontWeight: 'bold',
                              lineHeight: '0.24rem',
                              color: 'rgba(0, 0, 0, 0.85)',
                            }}
                          >
                            {/*  如果有编辑时显示的icon  */}
                            <span className={styles.tabpane_icon}>
                              {item.hasEdited ? <FormOutlined /> : <i className="iconfont icon-FlinkSQLrenwu" />}
                            </span>
                            {item.name}
                          </div>
                        </Dropdown>
                      }
                      key={String(item.id)}
                    >
                      <MonacoEditor
                        taskId={item.resourceId}
                        fatcherType={item.fatcherType}
                        editorTaskItem={item}
                        tabKey={item.id}
                        nodeId={item.nodeId}
                        hasEdited={item.hasEdited || false}
                        editorContentChange={this.editorContentChange}
                        taskParamValChange={this.taskParamValChange}
                        curstoMvariablesArrMr={this.props.curstoMvariablesArrMr}
                        curstoMvariablesArr={this.props.curstoMvariablesArr}
                        curstoMvariablesTask={this.curstoMvariablesTask}
                      />
                    </TabPane>
                  ))}
                </Tabs>
              </div>
            ) : (
              <div className={`dark_layout_node_box ${styles.none_box}`}>
                <div className={styles.explain}>
                  <img className={styles.empty_page_img} src={emptyImgNotWiFi} alt="" />
                  <div className={styles.empty_page_text}>
                    <BlueSquare
                      style={{
                        width: '3.45rem',
                      }}
                    />
                    打开或新建作业开发
                  </div>
                  <div className={styles.empty_page_content}>
                    作业开发提供了一套快速开发的WEB-SQL IDE工具
                  </div>
                  <Button
                    type="primary"
                    size="large"
                    className={styles.empty_page_button}
                    onClick={() => { Bus.emit('ShowTaskModal') }}
                  >
                    新建作业开发
                  </Button>
                </div>
              </div>
            )}
          </div>
        </div>
        {/*  编辑后关闭弹框确认  */}
        <Modal
          title="提示"
          visible={closeModalVisible}
          destroyOnClose
          onCancel={() => {
            this.setState({
              closeModalVisible: false,
            })
          }}
          footer={
            <div>
              {/*  不保存任务，关闭标签和弹窗  */}
              <Button
                onClick={() => {
                  this.setState(
                    {
                      closeModalVisible: false,
                    },
                    () => {
                      this.onEditTask(currentClosingTask.id, true)
                    },
                  )
                }}
              >
                否
              </Button>
              {/*  保存任务，并关闭标签和弹窗  */}
              <Button
                type="primary"
                onClick={() => {
                  this.setState(
                    {
                      closeModalVisible: false,
                    },
                    () => {
                      Bus.emit(
                        'datadevEditorSave',
                        currentClosingTask.id,
                      )
                      this.onEditTask(currentClosingTask.id, true)
                    },
                  )
                }}
              >
                是
              </Button>
              <Button
                onClick={() => {
                  this.setState({
                    closeModalVisible: false,
                  })
                }}
              >
                取消
              </Button>
            </div>
          }
        >
          <div className="dele-text">
            <i />
            <div>
              <span
                style={{
                  display: 'inline-block',
                  float: 'left',
                }}
              >
                是否保存对任务
                <span style={{ color: 'rgb(245, 71, 67)' }}>
                  {currentClosingTask?.name}
                </span>
                的修改？
              </span>
            </div>
          </div>
        </Modal>
      </div>
    )
  }
}
